package thread;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import util.Tools;

public class QuickSort {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> tm = Tools.getThousandNums();
        List<Integer> ttm = Tools.getTenThousandNums();
        List<Integer> htm = Tools.getHundredThousandNums();
        List<Integer> mn = Tools.getMillionNums();
        
        int count = mn.size();
        int rate = 50000;
        int cur = count / rate;
        int las = count % rate;
        CountDownLatch countDown = new CountDownLatch(3 + cur + (las <= 0 ? 0 : 1));
        // 此处分解1百万整数集，根据rate值来平均分解。
        List<Integer> sub_mn= new ArrayList<Integer>();
        for (int i = 0; i < cur; i++) {
            if (i == 0) 
                sub_mn = mn.subList(0, rate);
            else 
                sub_mn = mn.subList((i - 1) * rate, i * rate);
            Thread t = new Thread(new QuickSortHandler(sub_mn, countDown));
            t.start();
        }
        if (las > 0) {
            sub_mn = mn.subList((cur * rate), (cur * rate) + las);
            Thread t = new Thread(new QuickSortHandler(sub_mn, countDown));
            t.start();
        }
        
        
        long startTime = Calendar.getInstance().getTimeInMillis();
        Thread t1 = new Thread(new QuickSortHandler(tm, countDown));
        t1.start();
        Thread t2 = new Thread(new QuickSortHandler(ttm, countDown));
        t2.start();
        Thread t3 = new Thread(new QuickSortHandler(htm, countDown));
        t3.start();
        
        countDown.await();
        long endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("开始时间: " + startTime);
        System.out.println("结束时间: " + endTime);
        System.out.println("多线程方式对整数集进行排序处理，使用时间(毫秒数):" + (endTime - startTime));
    }
}
